<template>
    <div class="singer" ref="singer">
      <list-view ref="listview" :data="singers" @select="selectSinger"></list-view>
      <router-view></router-view>
    </div>
</template>

<script>
import {getSingerList} from 'api/singer'
import {ERR_OK} from 'api/config'

import Singer from 'common/js/singer'
import ListView from 'base/listview/listview'
import {playlistMixin} from 'common/js/mixin'
import {mapMutations} from 'vuex'

const HOT_NAME = '热门'
const HOT_SINGER_LEN = 10 // 热门歌手10个

export default {
  name: 'singer',
  data () {
    return {
      singers: []
    }
  },
  created () {
    this._getSingerList()
  },
  mixins: [playlistMixin],
  methods: {
    handlePlaylist (playlist) {
      const bottom = playlist.length > 0 ? '60px' : ''
      this.$refs.singer.style.bottom = bottom
      this.$refs.listview.refresh()
    },
    // 歌手列表排序
    _normalizeSinger (list) {
      let map = {
        hot: {
          title: HOT_NAME,
          items: []
        }
      }
      list.forEach((item, idx) => {
        // 热门歌手
        if (idx < HOT_SINGER_LEN) {
          map.hot.items.push(new Singer({
            id: item.Fsinger_mid,
            name: item.Fsinger_name
          }))
        }
        const key = item.Findex
        // 按照首字母
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push(new Singer({
          id: item.Fsinger_mid,
          name: item.Fsinger_name
        }))
      })
      // 列表排序
      let hot = [] // 热门歌手
      let rest = [] // 首字母排序
      for (let key in map) {
        let val = map[key]
        if (val.title.match(/[a-zA-Z]/)) {
          rest.push(val)
        } else if (val.title === HOT_NAME) {
          hot.push(val)
        }
      }
      rest.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      return hot.concat(rest)
    },
    selectSinger (singer) {
      this.$router.push({
        path: `/singer/${singer.id}`
      })
      this.setSinger(singer)
    },
    async _getSingerList () {
      let result = await getSingerList()
      if (result.code === ERR_OK) {
        this.singers = this._normalizeSinger(result.data.list)
      } else {
        console.log('获取歌手列表失败')
      }
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    })
  },
  components: {ListView}
}
</script>

<style lang="less" scoped>
  .singer {
    position: fixed;
    top: 88px;
    bottom: 0;
    width: 100%;
  }
</style>
